package com.strongbj.iot.devices.dam.request.handle.dam;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.common.NetMapping;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.request.entity.RackCodeEntity;
import com.strongbj.iot.devices.dam.request.handle.damtoscreen.CommandToScreenHandle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

class GetParamsHandle implements IMessageHandle<MQMessageOfDAM, Object> {
	private static Logger logger = LogManager.getLogger(CommandToScreenHandle.class.getName());
	private static final byte[] EMPTY_DATAS = {}; // 空参数
	private final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂
	/**
	 * 执行的查看命令值，不同值查看不同内容
	 */
	private byte command;
	/**
	 * 获取到的命令编码
	 */
	private String actionCode;

	public byte getCommand() {
		return command;
	}

	public void setCommand(byte command) {
		this.command = command;
	}

	public String getActionCode() {
		return actionCode;
	}

	public void setActionCode(String actionCode) {
		this.actionCode = actionCode;
	}

	public GetParamsHandle(String actionCode, byte command) {
		this.setActionCode(actionCode);
		this.setCommand(command);
	}

	@Override
	public boolean isHandle(MQMessageOfDAM t) {
		if (t.getActioncode().equals(this.actionCode)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 将设置网络参数的信息发送到硬件
	 */
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfDAM t) {
		final RackCodeEntity rc = ((JSONObject) t.getAwsPostdata()).toJavaObject(RackCodeEntity.class);
		Channel channel = NetMapping.getInstance().getChannel(rc.getRackConverCode());
		ITaskManager taskManager = DAMManager.getTaskManager(rc.getRackConverCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {

			@Override
			protected void taskRun() {
				sendDatasToDAM(channel, t, rc);
			}
		});
		return null;
	}

	private void sendDatasToDAM(Channel channel, MQMessageOfDAM t, RackCodeEntity rc) {
		if (channel != null && channel.isActive()) {
			final byte[] datas = RackCodeEntity2Bytes(t.getTimestamp(), rc);
			ByteBuf bs = Unpooled.copiedBuffer(datas);
			ChannelFuture cf = channel.writeAndFlush(bs);
			// TODO 添加监听,查看发送情况DEBUG
			cf.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						logger.info("WEB下发命令成功 编号:{} 下发命令={}  ", rc.getRackConverCode(),
								ByteUtil.byteArrToHexString(datas, true));
					} else {
						logger.error("WEB下发命令失败 编号:{} 下发命令={}  ", rc.getRackConverCode(),
								ByteUtil.byteArrToHexString(datas, true));
					}
				}

			});
		} else {
			logger.error("{} 主机没有找到指定channel", rc.getRackConverCode());
		}
	}

	/**
	 * 网络参数对象转byte数组
	 * 
	 * @param np
	 * @return
	 */
	private byte[] RackCodeEntity2Bytes(long time, RackCodeEntity rc) {
		// 创建设置目标服务器的指令
		byte[] datas = damMessageFactory.createDAMMessage(ByteUtil.longToBytes(time), rc.getRackConverCode(), // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				this.command, // 命令
				EMPTY_DATAS // 空参数
		); // 通过dam消息工厂获取指令
		return datas;
	}
}